#include "SkinApp.h"
#include "UdtSkinObjectEnginer.h"
#include "SkinXML.h"
#include "SkinObjManager.h"

CSkinApp* CSkinApp::m_pSkinApp = NULL;
CSkinApp::CSkinApp( HINSTANCE hInstance )
{
    m_UdtObjectEnginer = NULL;
    HRESULT hRes = ::CoInitialize( NULL );
    // If you are running on NT 4.0 or higher you can use the following call instead to
    // make the EXE free threaded. This means that calls come in on a random RPC thread.
    //	HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
    ATLASSERT( SUCCEEDED( hRes ) );
    // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
    ::DefWindowProc( NULL, 0, 0, 0L );
    AtlInitCommonControls( ICC_BAR_CLASSES );	// add flags to support other controls
    hRes = _Module.Init( NULL, hInstance );
    ATLASSERT( SUCCEEDED( hRes ) );
}


CSkinApp::~CSkinApp( void )
{
    if ( NULL != m_UdtObjectEnginer )
    {
        delete m_UdtObjectEnginer;
        m_UdtObjectEnginer = NULL;
    }

    CSkinObjManager* pObjMgr = CSkinObjManager::GetHinstance();

    if ( NULL != pObjMgr )
    {
        delete pObjMgr;
        pObjMgr = NULL;
    }

    _Module.Term();
    ::CoUninitialize();
}

BOOL CSkinApp::LoadSkinFile( LPCTSTR lpszSkinFile, SKIN_SRC_TYPE skinSrcType/* =SKIN_TYPE_XML */ )
{
    BOOL bRet = FALSE;
    CSkinFile* pSkinFile = NULL;

    if ( SKIN_TYPE_XML == skinSrcType )
    {
        pSkinFile = new CSkinXML( lpszSkinFile );
    }

    if ( NULL != pSkinFile )
    {
        if ( ( pSkinFile->LoadSkinFile() ) && ( pSkinFile->Parse() ) )
        {
            bRet = TRUE;
        }

        delete pSkinFile;
        pSkinFile = NULL;
    }

    return bRet;
}

int CSkinApp::Run( LPTSTR lpstrCmdLine /* = NULL */, int nCmdShow /* = SW_SHOWDEFAULT */ )
{
    int nRet = 0;
    CMessageLoop theLoop;
    _Module.AddMessageLoop( &theLoop );
    nRet = theLoop.Run();
    _Module.RemoveMessageLoop();
    return nRet;
}

void CSkinApp::SetUdtObjEnginer( CUdtSkinObjectEnginer* pSkinObjEnginer )
{
    m_UdtObjectEnginer = pSkinObjEnginer;
}

CSkinApp* CSkinApp::GetInstance()
{
    if ( NULL == m_pSkinApp )
    {
        m_pSkinApp = new CSkinApp( GetModuleHandle( NULL ) );
    }

    return m_pSkinApp;
}

CUdtSkinObjectEnginer* CSkinApp::GetUdtEnginer()
{
    return m_UdtObjectEnginer;
}

void CSkinApp::Release()
{
    delete m_pSkinApp;
}


// CSkinObject* CSkinApp::GetMainWnd()const
//{
//    return AfxGetSkinMgr()->GetSkinObjMgr()->FindObject(1);
//}